package com.club.football.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.club.football.common.UserHolder;
import com.club.football.dto.ChangePwdDto;
import com.club.football.dto.LoginDto;
import com.club.football.dto.PageDto;
import com.club.football.dto.UserSaveDto;
import com.club.football.entity.User;
import com.club.football.mapper.UserMapper;
import com.club.football.req.UserPageReq;
import com.club.football.service.UserService;
import com.club.football.utils.BeanUtils;
import com.club.football.utils.FileUtils;
import com.club.football.utils.R;
import com.club.football.vo.UserVo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.stream.Collectors;

import static com.club.football.common.CommonConstants.*;
import static com.club.football.utils.FileUtils.toMd5;
import static com.club.football.utils.JwtHelper.createToken;

/**
 * 用户服务实现
 *
 * @author 1
 * @date 2024/01/09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public R<UserVo> queryById(Long userId) {
        User user = baseMapper.selectById(userId);
        UserVo userVo = BeanUtils.copier(user, new UserVo());
        String userImage = userVo.getUserImage();
        userVo.setUserImage(FileUtils.getUrl(userImage));
        return R.ok(userVo, GET_INFO_OK);
    }

    @Override
    public R<String> login(LoginDto loginDto) {
        User user = lambdaQuery().eq(User::getAcc, loginDto.getAccount()).one();
        if (user == null) {
            return R.failed("用户名密码错误");
        }
        String password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        boolean login = user.getPwd().equals(password);
        if (!login) {
            return R.failed("用户名密码错误");
        }
        return R.ok(createToken(user), "登录成功");
    }

    @Override
    public R<Page<UserVo>> userPage(PageDto<User> pageDto, UserPageReq pageReq) {
        lambdaQuery().like(StringUtils.isNotBlank(pageReq.getAcc()), User::getAcc, pageReq.getAcc())
                .eq(StringUtils.isNotBlank(pageReq.getPhone()), User::getPhone, pageReq.getPhone())
                .page(pageDto);
        Page<UserVo> userVoPage = new Page<>();
        List<UserVo> collect = pageDto.getRecords().stream()
                .map(e -> BeanUtils.copier(e, new UserVo())).collect(Collectors.toList());
        userVoPage.setRecords(collect);
        userVoPage.setTotal(pageDto.getTotal());
        return R.ok(userVoPage, GET_INFO_OK);
    }

    @Override
    public R<String> saveUser(UserSaveDto userSaveDto) {
        User user = BeanUtils.copier(userSaveDto, new User());
        Long userId = UserHolder.getUser().getUserId();
        user.setUpdateBy(userId);
        if (user.getUserId() != null) {
            updateById(user);
            return R.ok(EDIT_OK_MSG);
        }
        user.setCreateBy(userId);
        user.setPwd(toMd5(DEFAULT_PASSWORD));
        save(user);
        return R.ok(SAVE_OK_MSG);
    }

    @Override
    public R<String> changePwd(ChangePwdDto dto) {
        Long userId = UserHolder.getUser().getUserId();
        User user = getById(userId);
        if (!user.getPwd().equals(toMd5(dto.getPassword()))) {
            return R.failed("密码错误");
        }
        lambdaUpdate().set(User::getPwd, toMd5(dto.getNewPassword()))
                .eq(User::getUserId, userId)
                .update();
        return R.ok(EDIT_OK_MSG);
    }

    @Override
    public R<String> changePhone(UserSaveDto dto) {
        if (StringUtils.isBlank(dto.getPhone()) || dto.getPhone().length() != PHONE_LENGTH) {
            return R.failed("手机号不合法");
        }
        Long userId = UserHolder.getUser().getUserId();
        lambdaUpdate().eq(User::getUserId, userId).set(User::getPhone, dto.getPhone()).update();
        return R.ok(EDIT_OK_MSG);
    }
}
